package com.shop.cereshop.app.dl.logic.utils;

/**
 * @author: 况鑫威
 * @Date: 2021/6/19
 * @Time: 20:18
 * @ClassName: Js_Sign
 * @Description: com.shop.cereshop.app.dl.logic.utils
 */

import com.alibaba.fastjson.JSONObject;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class JS_Sign {

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    @SuppressWarnings("rawtypes")
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


    public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!(ip == null || ip.trim().length() == 0) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!(ip == null || ip.trim().length() == 0) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    @SuppressWarnings("rawtypes")
    public static String createSign(String apiKey, String characterEncoding, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + apiKey);
        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    public static String CreateNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    /**
     * 解析xml
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Map doXMLParse(String strxml) throws Exception {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }
        //关闭流
        in.close();
        return m;
    }

    /**
     * 获取子结点的xml
     */
    @SuppressWarnings("rawtypes")
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }

    public static Map<String, String> sign(String jsapi_ticket, String url, String appid) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //  System.out.println(string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("noncestr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", appid);
        return ret;
    }
    /**
     * 功能描述: 获取getjsapiTicket
     * @Param: [appid, secret, url, request]
     * @return: java.lang.String
     * @Author: 况鑫威
     * @Date: 2021/6/25
     * @Time: 16:23
     */

    public static String getjsapiTicket(String appid, String secret, StringRedisService redisService){
        /*
         * 获取accessToken
         * */
        //获取域中的accessToken
//        Object accessToken = null;
        String accessToken = (String) redisService.get(appid + secret + "accessToken");
        Map map = null;
        //如果过期了则重新取一个
        if(accessToken == null || "".equals(accessToken)){
            try{
                accessToken = WeixinUtil.getAccessToken(appid, secret);
//                accessToken = map.get("access_token").toString();
                redisService.set(appid + secret + "accessToken",accessToken, 120*60*1000);
            }catch (Exception e){
                e.printStackTrace();
                return "";
            }
        }
        /*
         * 获取jsapi_ticket
         * */
//        Object jsapi_ticket = null;
        Object jsapi_ticket = redisService.get(appid + "jsapi_ticket_session");
        JSONObject json = null;
        if (jsapi_ticket == null || "".equals(jsapi_ticket)) {
            json = MyWeixinUtil.httpRequest("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi", "GET", "");
            jsapi_ticket = json.get("ticket");
            System.out.println(jsapi_ticket);
            redisService.set(appid + "jsapi_ticket_session",jsapi_ticket,120*60*1000);
        }

        //把缓存中的token保存下来,对比
        String temp = accessToken;
        //判断是否有错误码,有则说明没有调到,则重新调用一次
        if(jsapi_ticket == null && !WeixinUtil.isTokenFlag(json)){
            accessToken = WeixinUtil.getAccessToken(appid, secret);
            //如果相等,说明没有更新,直接调用微信的接口
            if(temp.equals(accessToken)){
                accessToken = WeixinUtil.getAccessTokenTwo(appid, secret);
            }
//            accessToken = (String) map.get("access_token");
            redisService.set(appid + secret + "accessToken", accessToken, 120*60*1000);
            //重新调用刷新数据
            json = MyWeixinUtil.httpRequest("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi", "GET", "");
            jsapi_ticket = json.get("ticket");
            redisService.set(appid + "jsapi_ticket_session",jsapi_ticket,120*60*1000);
        }
        return (String)jsapi_ticket;
    }

    /**
     * 功能描述: 获取签名
     * @Param: [appid, secret, url, request]
     * @return: java.util.Map<java.lang.String,java.lang.String>
     * @Author: 况鑫威
     * @Date: 2021/6/25
     * @Time: 16:24
     */
    public static Map<String, String> getJSSignMapResult(String appid, String secret, String url, StringRedisService redisService) {
        Map<String, String> ret;
        String jsapi_ticket = JS_Sign.getjsapiTicket(appid, secret, redisService);
        //签名
        ret = sign(jsapi_ticket, url, appid);
        return ret;
    }

}